﻿using System;
using System.Configuration;

namespace OperationPlugins.Applications.MongoDB
{
    /// <summary>
    /// Used to build MongoDB connection strings.
    /// </summary>
    internal sealed class ConnectionStringBuilder
    {
        private const string ConnectionStringName = "OperationPlugins.Applications.MongoDB";

        private readonly AppInstanceIndex _index;

        /// <summary>
        /// Initializes a new instance of the ConnectionStringBuilder class.
        /// </summary>
        internal ConnectionStringBuilder()
        {            
        }

        /// <summary>
        /// Initializes a new instance of the ConnectionStringBuilder class.
        /// </summary>
        /// <param name="index">AppInstance index</param>
        internal ConnectionStringBuilder(AppInstanceIndex index)
        {
            if (index == null)
            {
                throw new ArgumentNullException("index");
            }

            _index = index;
        }

        /// <summary>
        /// Returns the MongoDB connection string.
        /// </summary>
        /// <returns>The MongoDB connection string.</returns>
        internal string GetConnectionString()
        {
            string connectionString;

            if (_index == null || _index.UseDefaultConnectionString)
            {
                ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[ConnectionStringName];
                if (settings == null)
                {
                    throw new InvalidOperationException(string.Format("Could not find the connection string named {0} from the application configuration file.", ConnectionStringName));
                }
                connectionString = settings.ConnectionString;
            }
            else
            {
                connectionString = _index.ConnectionString;
            }

            return connectionString;            
        }

    }
}
